﻿#include "warehousing.h"
#include "ui_warehousing.h"


Warehousing::Warehousing(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Warehousing)
{
    ui->setupUi(this);
    ui->tableWidget->verticalHeader()->setVisible(false);
    ui->tableWidget->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
    ui->tableWidget->setFocusPolicy(Qt::NoFocus);
    ui->tableWidget->setContextMenuPolicy(Qt::CustomContextMenu);
    ui->tableWidget->horizontalHeader()->setSectionResizeMode(1,QHeaderView::Fixed);//第二列“产品选择”宽度设置
    ui->tableWidget->setColumnWidth(1,75);

    tip_confirm_checkbox=new QLabel(this);
    tip_confirm_checkbox_2=new QLabel(this);

    RightClickMenu=new QMenu(ui->tableWidget);
    m_addAction=new QAction(QString::fromUtf8("插入"),this);
    m_deleteAction=new QAction(QString::fromUtf8("删除"),this);
    RightClickMenu->addAction(m_addAction);
    RightClickMenu->addAction(m_deleteAction);

    connect(ui->tableWidget,SIGNAL(customContextMenuRequested(QPoint)),this,SLOT(RightClickSlot(QPoint)));
    connect(RightClickMenu,SIGNAL(triggered(QAction*)),this,SLOT(RightClickAddRow(QAction*)));
    connect(RightClickMenu,SIGNAL(triggered(QAction*)),this,SLOT(RightClickDeleteRow(QAction*)));

    //查询
    QSqlQuery sql_query;
    sql_query.exec("select * from testplanning order by 序号 asc");
    if(!sql_query.exec())
     {
       qDebug()<<sql_query.lastError();
     }
    else
     {   //行标志
       while(sql_query.next())
         {
           QString  no= sql_query.value(0).toString();
           QString  name= sql_query.value(1).toString();
           QString  code= sql_query.value(2).toString();
           QString ordernum = sql_query.value(3).toString();
           QString  storednum= sql_query.value(4).toString();
           QString tostorenum=sql_query.value(5).toString();
           QString unit=sql_query.value(6).toString();
           QString batchno=sql_query.value(7).toString();
//           qDebug()<<name;

           ui->tableWidget->setRowCount(k+1);

           ui->tableWidget->setItem(k,0,new QTableWidgetItem(no));
           ui->tableWidget->item(k, 0)->setTextAlignment(Qt::AlignCenter);//居中显示
           ui->tableWidget->setItem(k,1,new QTableWidgetItem(""));
           ui->tableWidget->item(k, 1)->setTextAlignment(Qt::AlignCenter);//居中显示
           ui->tableWidget->setItem(k,2,new QTableWidgetItem(name));
           ui->tableWidget->item(k, 2)->setTextAlignment(Qt::AlignCenter);//居中显示
           ui->tableWidget->setItem(k,3,new QTableWidgetItem(code));
           ui->tableWidget->item(k, 3)->setTextAlignment(Qt::AlignCenter);//居中显示
           ui->tableWidget->setItem(k,4,new QTableWidgetItem(ordernum));
           ui->tableWidget->item(k, 4)->setTextAlignment(Qt::AlignCenter);//居中显示
           ui->tableWidget->setItem(k,5,new QTableWidgetItem(storednum));
           ui->tableWidget->item(k, 5)->setTextAlignment(Qt::AlignCenter);//居中显示
           ui->tableWidget->setItem(k,6,new QTableWidgetItem(tostorenum));
           ui->tableWidget->item(k, 6)->setTextAlignment(Qt::AlignCenter);//居中显示
           ui->tableWidget->setItem(k,7,new QTableWidgetItem(unit));
           ui->tableWidget->item(k, 7)->setTextAlignment(Qt::AlignCenter);//居中显示
           ui->tableWidget->setItem(k,8,new QTableWidgetItem(batchno));
           ui->tableWidget->item(k, 8)->setTextAlignment(Qt::AlignCenter);//居中显示
           k+=1;
           }
     }

    //准备combobox---ok
    ui->type_combo->clear();
    sql_query.prepare("select distinct 生产工单 from producing_orders ");
    sql_query.exec();
    QSqlRecord rec = sql_query.record();
    while(sql_query.next())
    {
        int orderplace = rec.indexOf("生产工单");
        QString  order= sql_query.value(orderplace).toString();
        ui->type_combo->addItem(order);
//        qDebug()<<order;
    }


}

Warehousing::~Warehousing()
{
    delete ui;
}

void Warehousing::RowInit(int index)
{
    ui->tableWidget->insertRow(index); //在最后一行的后面插入一行

    //在插入的行中输入产品选择按钮从数据库获得产品数据
    QPushButton *choose_btn = new QPushButton();
    choose_btn->setObjectName("choose_btn" + QString::number(index));
    choose_btn->setProperty("type", "databaseBtn"); //数据库按钮样式

    QWidget *widget = new QWidget();
    QHBoxLayout *layout = new QHBoxLayout();
    layout->setMargin(0);//一定要有
    layout->addWidget(choose_btn);
    layout->setAlignment(choose_btn, Qt::AlignCenter);//控件在布局中居中显示
    widget->setLayout(layout);

    ui->tableWidget->setCellWidget(index, 1, widget);//放在表格第2列
    connect(choose_btn, &QPushButton::clicked, this, &Warehousing::choose_btn_clicked);

    for(int i=0;i<ui->tableWidget->columnCount();i++)
    {
        if(i==1)    //为按钮列
            continue;
        QTableWidgetItem *item = new QTableWidgetItem();
        ui->tableWidget->setItem(index,i,item);
        ui->tableWidget->item(index,i)->setTextAlignment(Qt::AlignCenter);
    }
}

void Warehousing::RowDelete(int index)
{
    if(index!=-1)
    {
        for(int i=0;i<ui->tableWidget->columnCount();i++)
        {
            QWidget *widget=ui->tableWidget->cellWidget(index,i);
            //确保不为空
            if(widget)
            {
                ui->tableWidget->removeCellWidget(index,i);
                delete widget;  //释放
            }
        }
        ui->tableWidget->removeRow(index);
    }
}

void Warehousing::RightClickSlot(QPoint pos)
{

    QModelIndex index = ui->tableWidget->indexAt(pos);    //找到tableview当前位置信息
    iPosRow = index.row();    //获取到了当前右键所选的行数
    if(index.isValid())        //如果行数有效，则显示菜单
    {
        RightClickMenu->exec(QCursor::pos());
    }

}

void Warehousing::RightClickAddRow(QAction *act)
{
    if(act->text() == QString::fromUtf8("插入"))   //选中了插入这个菜单
    {
        RowInit(iPosRow);
    }
}

void Warehousing::RightClickDeleteRow(QAction *act)
{
    if(act->text() == QString::fromUtf8("删除"))   //选中了删除这个菜单
    {
        RowDelete(iPosRow);
    }
}

void Warehousing::choose_btn_clicked()
{
    QPushButton* btn = qobject_cast<QPushButton*>(this->sender());
    if (btn == nullptr)
        return;

    // 获取按钮所在的行
    QModelIndex qIndex = ui->tableWidget->indexAt(QPoint(btn->parentWidget()->frameGeometry().x(), btn->parentWidget()->frameGeometry().y()));
    row = qIndex.row();

    //按钮状态选择
    if(btn->property("type")=="check")
    {
        btn->setProperty("type","checked");
        style()->polish(btn);
        vecItemIndex.push_back(row);//存储选中的行号
    }
    else if(btn->property("type")=="checked")
    {
        btn->setProperty("type","check");
        style()->polish(btn);
        vecItemIndex.erase(std::remove(vecItemIndex.begin(), vecItemIndex.end(), row), vecItemIndex.end()); //删除选中的行号
    }
    else if(btn->property("type")=="databaseBtn")
    {
        //创建数据选择子界面
        dc=new DataChoose();
        dc->setTitle("选择产品");
        dc->myModel->setQuery(QString("SELECT ProductCode, ProductName, ProductType FROM product_data_table"));
        dc->myModel->setHeaderData(0,Qt::Horizontal,"产品编码");
        dc->myModel->setHeaderData(1,Qt::Horizontal,"产品名称");
        dc->myModel->setHeaderData(2,Qt::Horizontal,"产品类型");
        dc->show();
        //子界面向主界面传送选择的数据
        connect(dc,static_cast<void(DataChoose::*)(const QModelIndexList&)>(&DataChoose::singal_selectedItems),
                this, [this](const QModelIndexList& list)
        {
            for(int i=0;i<list.size();i++)
            {
                switch (i) {
                case 0:
                    ui->tableWidget->item(row,3)->setText(list[i].data().toString());
                    break;
                case 1:
                    ui->tableWidget->item(row,2)->setText(list[i].data().toString());
                    break;
                default:
                    break;
                }
            }

            //填写数据：工单派工数量、已入库数量、本次入库数量
            QSqlQuery query;
            int num = 0;//工单派工数量
            int already = 0;
            query.exec(QString("select 数量 from producing_orders where 生产工单 = '%1'").arg(ui->type_combo->currentText()));
            while(query.next())
            {
                num = query.value(0).toInt();
                qDebug()<<"数量：   "<<num;
            }
            ui->tableWidget->item(row,4)->setText(QString::number(num));
            query.exec(QString("select 本次入库数量 from testplanning where 生产工单 = '%1'").arg(ui->type_combo->currentText()));
            while(query.next())
            {
                already += query.value(0).toInt();
                qDebug()<<"已经数量：  "<<already;
            }
            ui->tableWidget->item(row,5)->setText(QString::number(already));
            ui->tableWidget->item(row,6)->setText(QString::number(num-already));

        });
    }
}

void Warehousing::on_add_btn_clicked()
{
    if(ui->add_btn->text()=="添加")
    {
        RowInit(ui->tableWidget->rowCount());
    }
    else if(ui->add_btn->text()=="取消操作")
    {
        for(int i=0;i<ui->tableWidget->rowCount();i++)
        {
            QWidget *widget=ui->tableWidget->cellWidget(i,1);
            if(widget)
            {
                QPushButton* btn = dynamic_cast<QPushButton*>(widget->layout()->itemAt(0)->widget());
                btn->setProperty("type","databaseBtn");
                style()->polish(btn);
            }
        }

        ui->delete_btn->setText(QString::fromUtf8("删除"));
        ui->delete_btn->setProperty("type","deleteData");
        style()->polish(ui->delete_btn);

        ui->add_btn->setText(QString::fromUtf8("添加"));
        ui->add_btn->setProperty("type","addData");
        style()->polish(ui->add_btn);
    }
}

void Warehousing::on_delete_btn_clicked()
{
    if(ui->delete_btn->text()=="删除")
    {
        for(int i=0;i<ui->tableWidget->rowCount();i++)
        {
            QWidget *widget=ui->tableWidget->cellWidget(i,1);
            if(widget)
            {
                QPushButton* btn = dynamic_cast<QPushButton*>(widget->layout()->itemAt(0)->widget());
                btn->setProperty("type","check");
                style()->polish(btn);
            }
        }
        ui->delete_btn->setText(QString::fromUtf8("删除选中"));
        ui->delete_btn->setProperty("type","deleteConfirm");
        style()->polish(ui->delete_btn);

        ui->add_btn->setText(QString::fromUtf8("取消操作"));
        ui->add_btn->setProperty("type","deleteCancel");
        style()->polish(ui->add_btn);
    }
    else if(ui->delete_btn->text()=="删除选中")
    {
        sort(vecItemIndex.rbegin(), vecItemIndex.rend());
        for (unsigned int i = 0 ; i < vecItemIndex.size(); i++)
        {
            RowDelete(vecItemIndex[i]);
        }
        vecItemIndex.clear();  //清空容器
        vecItemIndex.shrink_to_fit();   //将容器的容量缩减至和实际存储元素的个数相等，释放内存

        ui->delete_btn->setText(QString::fromUtf8("删除"));
        ui->delete_btn->setProperty("type","deleteData");
        style()->polish(ui->delete_btn);

        ui->add_btn->setText(QString::fromUtf8("添加"));
        ui->add_btn->setProperty("type","addData");
        style()->polish(ui->add_btn);

        for(int i=0;i<ui->tableWidget->rowCount();i++)
        {
            QWidget *widget=ui->tableWidget->cellWidget(i,1);
            if(widget)
            {
                QPushButton* btn = dynamic_cast<QPushButton*>(widget->layout()->itemAt(0)->widget());
                btn->setProperty("type","databaseBtn");
                style()->polish(btn);
            }
        }

    }
}

void Warehousing::on_select_member_clicked()
{
    //创建数据选择子界面
    dc=new DataChoose();
    dc->setTitle("选择质检员");
    dc->myModel->setQuery("SELECT id, username, position FROM dm_user WHERE delete_flag=0");
    dc->myModel->setHeaderData(0,Qt::Horizontal,"编号");
    dc->myModel->setHeaderData(1,Qt::Horizontal,"姓名");
    dc->myModel->setHeaderData(2,Qt::Horizontal,"职位");
    dc->show();
    //子界面向主界面传送选择的数据
    connect(dc,static_cast<void(DataChoose::*)(const QModelIndexList&)>(&DataChoose::singal_selectedItems),
            this, [this](const QModelIndexList& list)
    {
        ui->select_member->setText(list[0].data().toString() + "(" + list[1].data().toString() + ")");
        ui->select_member->setProperty("type","SelectMember_ed");
        style()->polish(ui->select_member);

    });
}

void Warehousing::on_select_member_2_clicked()
{
    //创建数据选择子界面
    dc=new DataChoose();
    dc->setTitle("选择质检员");
    dc->myModel->setQuery("SELECT id, username, position FROM dm_user WHERE delete_flag=0");
    dc->myModel->setHeaderData(0,Qt::Horizontal,"编号");
    dc->myModel->setHeaderData(1,Qt::Horizontal,"姓名");
    dc->myModel->setHeaderData(2,Qt::Horizontal,"职位");
    dc->show();
    //子界面向主界面传送选择的数据
    connect(dc,static_cast<void(DataChoose::*)(const QModelIndexList&)>(&DataChoose::singal_selectedItems),
            this, [this](const QModelIndexList& list)
    {
        ui->select_member_2->setText(list[0].data().toString() + "(" + list[1].data().toString() + ")");
        ui->select_member_2->setProperty("type","SelectMember_ed");
        style()->polish(ui->select_member_2);

    });
}

void Warehousing::on_submit_btn_2_clicked()
{
//    IDGenerate();
    if(ui->confirm_checkBox_5->isChecked()&&ui->confirm_checkBox_6->isChecked())
    {
        int ret = QMessageBox::question(this, "上传入库单","确认上传", QMessageBox::Yes, QMessageBox::No);
        if(ret == QMessageBox::Yes)
        {

            int rowIdx = ui->tableWidget->rowCount();
//            qDebug() << rowIdx-k;
            QSqlQuery query;
            while(rowIdx-k){
                QString item_no = ui->tableWidget->item(k,0)==nullptr? "": ui->tableWidget->item(k,0)->text();
                QString item_name = ui->tableWidget->item(k,2)==nullptr? "": ui->tableWidget->item(k,2)->text();
                QString item_code = ui->tableWidget->item(k,3)==nullptr? "": ui->tableWidget->item(k,3)->text();
                QString item_ordernum = ui->tableWidget->item(k,4)==nullptr? "": ui->tableWidget->item(k,4)->text();
                QString item_storednum = ui->tableWidget->item(k,5)==nullptr? "": ui->tableWidget->item(k,5)->text();
                QString item_tostorenum = ui->tableWidget->item(k,6)==nullptr? "": ui->tableWidget->item(k,6)->text();
                QString item_unit = ui->tableWidget->item(k,7)==nullptr? "": ui->tableWidget->item(k,7)->text();
                QString item_batchno = ui->tableWidget->item(k,8)==nullptr? "": ui->tableWidget->item(k,8)->text();
                QString insert_row = QString("insert into testplanning(序号,产品名称,产品编码,工单派工数量,已入库数量,本次入库数量,单位,产品批次号,生产工单) values(%1,'%2','%3',%4,'%5','%6','%7','%8','%9')").
                        arg(item_no).arg(item_name).arg(item_code).arg(item_ordernum).arg(item_storednum).arg(item_tostorenum).arg(item_unit).arg(item_batchno).arg(ui->type_combo->currentText());
//                qDebug() << insert_row;
                query.exec(insert_row);
                k++;
            }

            QMessageBox::information(this,"上传入库单","上传成功");
            //不再显示tip
            if(tip_confirm_checkbox)
                 tip_confirm_checkbox->hide();
                 tip_confirm_checkbox_2->hide();
        }

    }
    else if(ui->confirm_checkBox_5->isChecked()==false)
    {
        tip_confirm_checkbox->setText(QString::fromUtf8("*必填"));
        tip_confirm_checkbox->setStyleSheet("color:red;");
        QPoint posA = ui->confirm_checkBox_5->mapToGlobal(QPoint(0,0));
        QPoint posB = this->mapFromGlobal(QPoint(posA.x()+ui->confirm_checkBox->width(),posA.y()));
        tip_confirm_checkbox->move(posB);
        tip_confirm_checkbox->show();
    }
    if(ui->confirm_checkBox_6->isChecked()==false)
    {
        tip_confirm_checkbox_2->setText(QString::fromUtf8("*必填"));
        tip_confirm_checkbox_2->setStyleSheet("color:red;");
        QPoint posA = ui->confirm_checkBox_6->mapToGlobal(QPoint(0,0));
        QPoint posB = this->mapFromGlobal(QPoint(posA.x()+ui->confirm_checkBox->width(),posA.y()));
        tip_confirm_checkbox_2->move(posB);
        tip_confirm_checkbox_2->show();
    }
}

QString Warehousing::Status()
{
    QString work,
            plan;
    if(ui->confirm_checkBox->isChecked()==false&&ui->confirm_checkBox_2->isChecked()==false&&ui->confirm_checkBox_3->isChecked()==false&&ui->confirm_checkBox_4->isChecked()==false)
    {
        int note = QMessageBox::question(this, "注意","请完善工单及计划状态！", QMessageBox::Ok);
        if(note == QMessageBox::Ok)
        {
            QMessageBox::information(this,"上传入库单","待实现");
        }
    }
    if(ui->confirm_checkBox->isChecked())
    {
        work = QString::fromUtf8("已完结");
    }
    else work = QString::fromUtf8("已派工");
    if(ui->confirm_checkBox_3->isChecked())
    {
        work = QString::fromUtf8("已完结");
    }
    else work = QString::fromUtf8("已计划");
}

void Warehousing::on_update_btn_clicked()
{
    int currentRow = ui->tableWidget->currentIndex().row();
    QSqlQuery sql_query;

//    qDebug()<<"number:"<<number;
//    sql_query.exec(QString ("select * from testplanning where 序号 = '%1'").arg(number));
//    if(sql_query.next())
//    {
//        ui->ID_4->setText(sql_query.value(7).toString());
//
//    }

    //ID
    QString type=ui->type_combo_2->currentText(),
            time1=ui->datetime_1->dateToStr().remove(QChar('-'), Qt::CaseInsensitive),   //去除字符‘-’
            time2=ui->datetime_2->dateToStr().remove(QChar('-'), Qt::CaseInsensitive),
            limit;
    if(type=="原料库")
        limit=QString::fromUtf8("SCRK");
    else if(type=="成品库")
        limit=QString::fromUtf8("SCRK");
//    limit += ui->tableWidget->item(currentRow,2)->text();
    limit += time1;
    limit += time2;
    ui->ID_5->setText(limit);
//    QSqlQuery query= mydb->SortData("storage_record_table","StorageRecordID",false,"StorageRecordID",limit); //降序排列
//    if(query.next())
//    {
//        QString str=query.value(0).toString();
//        QString num=NumberIncrease(str.mid(11)); //截取后四位,自增
//        return limit+num;
//    }
//    else
//        return limit+"0001";


}

void Warehousing::on_type_combo_currentTextChanged(const QString &arg1)
{
    //查询，根据combobox
    ui->tableWidget->setRowCount(0);
    QSqlQuery sql_query;
    sql_query.exec(QString ("select * from testplanning where 生产工单 = '%1' order by 序号 asc").arg(ui->type_combo->currentText()));
    if(!sql_query.exec())
     {
       qDebug()<<sql_query.lastError();
     }
    else
     {   //行标志
        k = 0;
       while(sql_query.next())
         {
           QString  no= sql_query.value(0).toString();
           QString  name= sql_query.value(1).toString();
           QString  code= sql_query.value(2).toString();
           QString ordernum = sql_query.value(3).toString();
           QString  storednum= sql_query.value(4).toString();
           QString tostorenum=sql_query.value(5).toString();
           QString unit=sql_query.value(6).toString();
           QString batchno=sql_query.value(7).toString();
//           qDebug()<<name;

           ui->tableWidget->setRowCount(k+1);

           ui->tableWidget->setItem(k,0,new QTableWidgetItem(no));
           ui->tableWidget->item(k, 0)->setTextAlignment(Qt::AlignCenter);//居中显示
           ui->tableWidget->setItem(k,1,new QTableWidgetItem(""));
           ui->tableWidget->item(k, 1)->setTextAlignment(Qt::AlignCenter);//居中显示
           ui->tableWidget->setItem(k,2,new QTableWidgetItem(name));
           ui->tableWidget->item(k, 2)->setTextAlignment(Qt::AlignCenter);//居中显示
           ui->tableWidget->setItem(k,3,new QTableWidgetItem(code));
           ui->tableWidget->item(k, 3)->setTextAlignment(Qt::AlignCenter);//居中显示
           ui->tableWidget->setItem(k,4,new QTableWidgetItem(ordernum));
           ui->tableWidget->item(k, 4)->setTextAlignment(Qt::AlignCenter);//居中显示
           ui->tableWidget->setItem(k,5,new QTableWidgetItem(storednum));
           ui->tableWidget->item(k, 5)->setTextAlignment(Qt::AlignCenter);//居中显示
           ui->tableWidget->setItem(k,6,new QTableWidgetItem(tostorenum));
           ui->tableWidget->item(k, 6)->setTextAlignment(Qt::AlignCenter);//居中显示
           ui->tableWidget->setItem(k,7,new QTableWidgetItem(unit));
           ui->tableWidget->item(k, 7)->setTextAlignment(Qt::AlignCenter);//居中显示
           ui->tableWidget->setItem(k,8,new QTableWidgetItem(batchno));
           ui->tableWidget->item(k, 8)->setTextAlignment(Qt::AlignCenter);//居中显示
           k+=1;
           }
     }

    ui->ID_2->setText(ui->type_combo->currentText());

}

QString Warehousing::IDGenerate()
{

}

//void Warehousing::on_tableWidget_itemSelectionChanged()
//{

//}

void Warehousing::on_tableWidget_itemClicked(QTableWidgetItem *item)
{
    QSqlQuery sql_query;
    int rowIdx = ui->tableWidget->currentRow();
    int temp = 0;
    int i = 0;
    ui->ID_4->setText(ui->tableWidget->item(rowIdx,8)->text());
//    sql_query.exec(QString("select 产品批次号 from testplanning where 生产工单 = '%1'").arg(ui->type_combo->currentText()));
//    while(sql_query.next())
//    {
//        QString  batchno= sql_query.value(0).toString();
//        if(i == rowIdx)
//        {
//            ui->ID_4->setText(batchno);
//        }
//        i++;
//    }

    sql_query.exec(QString("select 入库申请单号 from testplanning where 生产工单 = '%1'").arg(ui->type_combo->currentText()));
    while(sql_query.next())
    {
        QString flag = sql_query.value(0).toString();
        if(rowIdx == temp)
        {
            ui->ID_5->setText(flag);
            break;
        }
        else
        {
            QString order=ui->type_combo->currentText(),
                    time1=ui->datetime_1->dateToStr().remove(QChar('-'), Qt::CaseInsensitive),   //去除字符‘-’
                    time2=ui->datetime_2->dateToStr().remove(QChar('-'), Qt::CaseInsensitive),
                    batchnum=ui->ID_4->text(),
//                    workid=ui->tableWidget->item(rowIdx,7)->text(),
                    limit;
            limit=QString::fromUtf8("SCRK");
        //    limit += ui->tableWidget->item(currentRow,2)->text();
            limit += time1;
            limit += time2;
            limit += batchnum;
//            limit += workid;

            qDebug()<<limit;
            ui->ID_5->setText(limit);
        }
        temp++;
    }
}
